package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiPager;
import cn.com.yx.ms.domain.GlobalConfigModel;
import cn.com.yx.ms.domain.dbmodel.*;
import cn.com.yx.ms.domain.dev.EquipmentAndSiteModel;
import cn.com.yx.ms.domain.model.ModelControlMapModel;
import cn.com.yx.ms.domain.model.ModelControlModel;
import cn.com.yx.ms.domain.model.ModelMainModel;
import cn.com.yx.ms.domain.model.SimpleModel;
import cn.com.yx.ms.persistence.*;
import cn.com.yx.ms.service.IModelService;
import cn.com.yx.ms.service.ISysService;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.util.FileUtil;
import cn.yx.framework.util.ZipUtil;
import cn.yx.framework.view.ApiResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 栏目相关操作实现
 */
@Service
@Transactional
public class ModelServiceImpl implements IModelService {

    @Resource
    private ModelControlMapper modelControlMapper;

    @Resource
    private ModelMainMapper modelMainMapper;

    @Resource
    private ModelControlMapMapper modelControlMapMapper;
    @Resource
    private JmControlMapMapper jmControlMapMapper;
    @Resource
    private StlDevMapMapper stlDevMapMapper;
    @Resource
    private StlModelMainMapMapper stlModelMainMapMapper;
    @Resource
    private ISysService iSysService;
    // 模板文件(根目录)


    /**
     * 获取/查询栏目
     *
     * @param modelModel 栏目Bean
     * @return
     */
    @Override
    public ApiResult getAllModelControl(ModelControlModel modelModel) {
        // 翻页对象构建
        PageHelper.startPage(modelModel.getPage_pi(), modelModel.getPage_ps(), true);
        Page<ModelControlModel> page = (Page<ModelControlModel>) modelControlMapper.findAllModelControl(modelModel);

        ApiPager<ModelControlModel> apiPager = new ApiPager<>(modelModel.getPage_ps(),
                modelModel.getPage_pi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", apiPager);
    }

    /**
     * 新增栏目
     *
     * @param modelControl
     * @return
     */
    @Override
    public ApiResult addModelControl(ModelControl modelControl) {
        ApiResult result = null;

        // UUid
        modelControl.setGuid(UUID.randomUUID().toString());

        // 新增栏目时间
        modelControl.setCreatetime(new Date());

        // 是否删除
        modelControl.setIsdeleted(0);

        // 新增栏目接口调用
        int rt = modelControlMapper.insertSelective(modelControl);

        if (rt > 0) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "添加栏目成功", null);
        } else {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "添加栏目失败");
        }

        return result;
    }

    /**
     * 修改栏目
     *
     * @param modelControl 栏目Bean
     * @return
     */
    @Override
    public ApiResult editModelControl(ModelControl modelControl) {
        ApiResult result = null;

        // 修改栏目接口调用
        int rt = modelControlMapper.updateByPrimaryKeySelective(modelControl);

        if (rt > 0) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "修改栏目成功", null);
        } else {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "修改栏目失败");
        }
        return result;
    }

    /**
     * 停用栏目
     *
     * @param guid 栏目id
     * @return
     */
    @Override
    public ApiResult disableModelControl(String guid) {
        ApiResult result = null;

        // 停用栏目接口调用
        int rt = modelControlMapper.disableModelControl(guid);

        if (rt > 0) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "停用栏目成功", null);
        } else {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "停用栏目失败");
        }
        return result;
    }

    /**
     * 获取模板一览数据(分页)
     *
     * @param modelModel 模板Bean
     * @return
     */
    @Override
    public ApiResult getAllModelMain(ModelMainModel modelModel) {
        if (null != modelModel.getSortid() && modelModel.getSortid().equals("-1")) {
            modelModel.setSortid("");
        }
        if (null != modelModel.getIsuse() && modelModel.getIsuse() == -1) {
            modelModel.setIsuse(null);
        }


        PageHelper.startPage(modelModel.getPage_pi(), modelModel.getPage_ps(), true);
        List<ModelMainModel> modelList = modelMainMapper.findAllModelMain(modelModel);
        for (ModelMainModel modelMainModel : modelList) {
            modelMainModel.setThumbnail(BaseConstant.getServerConfig().getMediaurl() + "/template" + "/" + modelMainModel.getNo() + "/" + modelMainModel.getThumbnail());
        }
        Page<ModelMainModel> page = (Page<ModelMainModel>) modelList;
        ApiPager<ModelMainModel> apiPager = new ApiPager<>(modelModel.getPage_ps(),
                modelModel.getPage_pi(),
                page.getTotal(),
                page.getResult());

        List<ModelControlMapModel> modelControlMapModels = modelMainMapper.findAllModelControlMapModel();

        for (int i = 0; i < page.getTotal(); i++) {
            page.get(i).setModelControlList(new ArrayList<>());
            if (modelControlMapModels != null) {
                for (int j = 0; j < modelControlMapModels.size(); j++) {
                    if (page.get(i).getGuid().equals(modelControlMapModels.get(j).getModelid())) {
                        page.get(i).getModelControlList().add(modelControlMapModels.get(j));
                    }
                }
            }
        }

        //

        // region 子对象赋值

//        for (int i = 0; i < list.size(); i++) {
//            ModelMainModel model = list.get(i);
//            // 第一个对象
//            if("".equals(guid)){
//                guid = model.getGuid();
//                mapList.add(setModelMapBean(model));
//            } else {
//                if(guid.equals(model.getGuid())){
//                    mapList.add(setModelMapBean(model));
//                } else {
//                    guid = model.getGuid();
//                    ModelMainModel mainModel = list.get(i - 1);
//                    mainModel.setModelControlList(mapList);
//                    modelList.add(mainModel);
//                    mapList = new ArrayList<ModelControlMapModel>();
//                    mapList.add(setModelMapBean(model));
//                }
//            }
//
//            // 最后一个对象
//            if(i == list.size() - 1){
//                model.setModelControlList(mapList);
//                modelList.add(model);
//            }
//        }
//
//        List<ModelMainModel> returnList= PageUtil.getPageList(modelModel.getPage_ps(),modelModel.getPage_pi(),modelList);
//
//        ApiPager<ModelMainModel> returnApiPager = new ApiPager<>(modelModel.getPage_ps(),
//                modelModel.getPage_pi(),
//                modelList.size(),
//                returnList);

        // endregion

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "获取模板成功", apiPager);
    }

    /**
     * 栏目配置相关参数设置
     *
     * @param modelMainModel
     * @return
     */
    private ModelControlMapModel setModelMapBean(ModelMainModel modelMainModel) {
        ModelControlMapModel modelControlMapModel = new ModelControlMapModel();
        modelControlMapModel.setSourcetype(Integer.toString(modelMainModel.getSourcetype()));
//        modelControlMapModel.setAreano(modelMainModel.getAreano());
        modelControlMapModel.setControlid(modelMainModel.getControlid());
        modelControlMapModel.setControlname(modelMainModel.getControlname());
        modelControlMapModel.setAreano(StringUtils.isNotEmpty(modelMainModel.getAreanoname()) ? modelMainModel.getAreanoname() + "(" + modelMainModel.getAreano() + ")" : modelMainModel.getAreano());
        return modelControlMapModel;
    }

    /**
     * 新增模板
     *
     * @param modelMain 模板Bean
     * @return
     */
    @Override
    @Transactional
    public ApiResult addModelMain(ModelMainModel modelMain) {
        ApiResult result = null;

        // UUid
        String modelGuid = UUID.randomUUID().toString();
        modelMain.setGuid(modelGuid);

        // 新增栏目时间
        Date createDate = new Date();
        modelMain.setCreatetime(createDate);

        // 是否删除
        modelMain.setIsdeleted(0);

        // 新增栏目接口调用
        int rt = modelMainMapper.insertSelective(modelMain);

        if (rt > 0) {
            // 编辑模板栏目关系
            List<ModelControlMapModel> mapList = modelMain.getModelControlList();

            List<ModelControl> modelControls = new ArrayList<ModelControl>();

            for (ModelControlMapModel map : mapList) {
//                String controlId = UUID.randomUUID().toString();
                map.setGuid(UUID.randomUUID().toString());
                map.setCreatetime(createDate);
                map.setModelid(modelGuid);
//                map.setControlid(controlId);

                // 判断栏目id是否在栏目表中存在
                if (null == modelControlMapper.selectByPrimaryKey(map.getControlid())) {
                    ModelControl modelControl = new ModelControl();
                    modelControl.setGuid(map.getControlid());
                    modelControl.setMemo(map.getMemo());
                    modelControl.setName(map.getControlname());
                    modelControl.setSourcetype(Integer.parseInt(map.getSourcetype()));
                    modelControl.setIsenabled(1);
                    modelControl.setCreatetime(new Date());
                    modelControl.setIsdeleted(0);
                    modelControls.add(modelControl);
                }
            }

            // 模板栏目关系新规
            rt = modelControlMapMapper.insertModelControlMap(mapList);

            if (rt == 0) {
                return new ApiResult(AppConstant.MSG_FAILURE, false, "添加模板失败");
            } else {
                if (modelControls.size() > 0) {
                    modelControlMapper.insertModelControlList(modelControls);
                }
            }
        } else {
            return new ApiResult(AppConstant.MSG_FAILURE, false, "添加模板失败");
        }
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "添加模板成功", null);
    }

    /**
     * 修改模板
     *
     * @param modelMain 模板Bean
     * @return
     */
    @Override
    public ApiResult editModelMain(ModelMainModel modelMain) {
        ApiResult result = null;

        // 更新模板基础信息
        int rt = modelMainMapper.updateByPrimaryKeySelective(modelMain);

        if (rt > 0) {
            // 更新原来模板栏目关联信息
            rt = modelControlMapMapper.deleteByModelid(modelMain.getGuid());

            if (rt > 0) {
                // 编辑模板栏目关系
                List<ModelControlMapModel> mapList = modelMain.getModelControlList();

                for (ModelControlMap map : mapList) {
                    map.setGuid(UUID.randomUUID().toString());
                    map.setCreatetime(new Date());
                    map.setModelid(modelMain.getGuid());
                }

                // 模板栏目关系新规
                rt = modelControlMapMapper.insertModelControlMap(mapList);

                if (rt > 0) {
                    return new ApiResult().success(AppConstant.MSG_SUCCESS, "模板修改成功", null);
                }
            }
        }
        return new ApiResult(AppConstant.MSG_FAILURE, false, "模板修改失败");
    }

    /**
     * 获取栏目下拉框一览
     *
     * @return
     */
    @Override
    public ApiResult getModelControl() {
        // 获取栏目接口调用
        List<ModelControl> list = modelControlMapper.selectModelControl();

        return new ApiResult().success(AppConstant.MSG_SUCCESS, "获取栏目一览成功", list);
    }

    /**
     * 停用模板
     *
     * @param guid 模板id
     * @return
     */
    @Override
    public ApiResult disableModelMain(String guid) {
        ApiResult result = null;

        // 调用停用模板接口
        int rt = modelMainMapper.disableModelMain(guid);

        if (rt > 0) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "停用模板成功", null);
        } else {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "停用模板失败");
        }
        return result;
    }

//    /**
//     * 导出模板
//     * @param guids 模板id组
//     * @return
//     */
//    @Override
//    public ApiResult exportModel(String guids, HttpServletResponse res){
//        ApiResult apiResult = new ApiResult();
//        List<String> guidList = new ArrayList<String>();
//
//        boolean returnVal = false;
//
//        // 获取多选guid
//        for(String guid : guids.split(",")){
//            guidList.add(guid);
//        }
//
//        // 返回对象
//        List<ModelMainModel> modelList = new ArrayList<ModelMainModel>();
//
//        // 查询获取元对象
//        List<ModelMainModel> list = modelMainMapper.findModelMainList(guidList);
//
//        // 是否同一模板ID
//        String guid = "";
//
//        // 同一模板的栏目配置
//        List<ModelControlMapModel> mapList = new ArrayList<ModelControlMapModel>();
//
//        // 模板no
//        List<String> modelnoList = new ArrayList<String>();
//
//        JSONArray json = new JSONArray();
//        for(int i = 0;i<list.size();i++){
//            ModelMainModel model = list.get(i);
//            // 第一个对象
//            if("".equals(guid)){
//                guid = model.getGuid();
//                mapList.add(setModelMapBean(model));
//            } else {
//                if(guid.equals(model.getGuid())){
//                    mapList.add(setModelMapBean(model));
//                } else {
//                    guid = model.getGuid();
//                    ModelMainModel mainModel = list.get(i -1);
//                    mainModel.setModelControlList(mapList);
//                    modelList.add(mainModel);
//                    modelnoList.add(mainModel.getNo());
//                    json.add(mainModel);
//
//                    apiResult = writeToJson(json,mainModel.getNo());
//                    if(!apiResult.isSucc()){
//                        return apiResult;
//                    }
//
//                    mapList = new ArrayList<ModelControlMapModel>();
//                    mapList.add(setModelMapBean(model));
//                    json = new JSONArray();
//                }
//            }
//
//            // 最后一个对象
//            if(i == list.size() - 1){
//                model.setModelControlList(mapList);
//                modelList.add(model);
//                modelnoList.add(model.getNo());
//                json.add(model);
//
//                apiResult = writeToJson(json,model.getNo());
//                if(!apiResult.isSucc()){
//                    return apiResult;
//                }
//            }
//        }
//
//        return new ApiResult().success(AppConstant.MSG_SUCCESS, "模板导出成功", null);
//
////        return new ApiResult().success(AppConstant.MSG_SUCCESS, "导出模板成功", json);
//    }

    /**
     * 导入模板
     *
     * @param request
     * @return
     */
    @Override
    public ApiResult importModel(HttpServletRequest request) {
        String fileSavePath = BaseConstant.getUploadConfig().getFilepath() + "/import/modelzip";

        String fileName = "";

        //request强制转换注意
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

        // 将文件保存到指定目录
        if (mRequest != null) {
            try {
                fileName = mRequest.getFile("file").getOriginalFilename();
//                File fileForZip = new File(fileSavePath + "/" + fileName);
//                FileUtils.copyFile(fileForZip, (File)mRequest.getFile("file"));

                // 将上传zip文件保存到临时目录
                FileUtil.writeFile(fileSavePath,
                        fileName,
                        mRequest.getFile("file").getBytes());

                // 解压文件
                ZipUtil.decompress(fileSavePath + "/" + fileName, fileSavePath + "/" + FileUtil.getFileName(fileName));
            } catch (Exception ex) {
                return new ApiResult().success(AppConstant.MSG_FAILURE, "模板导入失败", null);
            }
        } else {
            return new ApiResult().success(AppConstant.MSG_FAILURE, "文件读取失败", null);
        }

        //读取json文件
        String fileContent = FileUtil.readFile(fileSavePath + "/" + FileUtil.getFileName(fileName) + "/model.json");
        JSONArray jsonArray = JSONArray.parseArray(fileContent);

        // 循环导入json数据
        for (int i = 0; i < jsonArray.size(); i++) {
            // 类型转换
            ModelMainModel modelMainModel = JSON.parseObject(jsonArray.get(i).toString(), ModelMainModel.class);
            //判断模板是否重复添加
            ApiResult apiResult1 = this.isRepeated(modelMainModel);
            if (!apiResult1.isSucc()) {
                return new ApiResult<>(AppConstant.MSG_FAILURE, "该模板已经存在!");
            }
            ApiResult apiResult = this.addModelMain(modelMainModel);

            if (!apiResult.isSucc()) {
                return new ApiResult().success(AppConstant.MSG_FAILURE, "数据导入失败", null);
            }
        }

        // 将模板文件拷贝到指定目录下
        String modelDataPath = BaseConstant.getUploadConfig().getModeldatapath();

        // 将上传zip文件保存到临时目录
        FileUtil.copyFile(new File(fileSavePath + "/" + FileUtil.getFileName(fileName) + "/" + fileName),
                new File(modelDataPath + "/" + fileName));

        return new ApiResult().success(AppConstant.MSG_SUCCESS, "模板导入成功", null);
    }

//    /**
//     * 将json写入文件
//     * @param object
//     * @throws IOException
//     */
//    public ApiResult writeToJson(JSONArray object, String modelNo)
//    {
//        FileInputStream fis = null;
//        BufferedInputStream bis = null;
//        FileOutputStream fos = null;
//        ZipOutputStream zos = null;
//
//        //
////        if(StringUtils.isEmpty(modelno)){
////            return new ApiResult().success(AppConstant.MSG_FAILURE, "导出失败!模板编号获取失败,请联系管理员", null);
////        }
//
//        // 防止重复模板好
////        List<String> simpleModel = new ArrayList<String>();
//
//        // 模板编号为空的场合
//        if(StringUtils.isEmpty(modelNo)){
//            return new ApiResult().success(AppConstant.MSG_FAILURE, "导出失败!模板的模板编号为空,请联系管理员", null);
//        }
//
//        // 过滤不存在模板号及重复模板号
//        File file = new File(BaseConstant.getUploadConfig().getFilepath() + "/template" + "/" + modelNo+".zip");
//        if(!file.exists()){
//            return new ApiResult().success(AppConstant.MSG_FAILURE, "导出失败!模板编号:" + modelNo + "的模板文件未找到,请联系管理员", null);
//        }
//
////        if(!simpleModel.contains(modelNo)){
////            simpleModel.add(modelNo);
////        }
//
//        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//
//            // 导出目录生成
////            String dirName = "model_" + sdf.format(new Date());
//            String exportPath = BaseConstant.getUploadConfig().getFilepath() + "/export/modelzip" + "/" + modelNo;
//
//            // 将对应的模板zip文件拷贝到目录下
////            for (String modelno : simpleModel) {
//                File fileForZip = new File(BaseConstant.getUploadConfig().getFilepath() + "/template" + "/" + modelNo + ".zip");
//                FileUtils.copyFile(fileForZip, new File(exportPath + "/" + modelNo + ".zip"));
////            }
//
//            // json文件做成
//            File fileJson = new File(exportPath + "/model.json");
//            ObjectMapper mapper = new ObjectMapper();
//            mapper.writeValue(fileJson, object);
//
//            // 压缩相关文件
//            File zipFile = new File(BaseConstant.getUploadConfig().getFilepath() + "/export/modelzip" + "/" + modelNo +".zip");
//
//            // 压缩源文件
//            File sourceFile = new File(exportPath);
//
//            if(!sourceFile.exists()){
//                return new ApiResult().success(AppConstant.MSG_FAILURE, "导出失败!待压缩文件不存在", null);
//            }
//
//            // 待压缩文件列表
//            File[] sourceFiles = sourceFile.listFiles();
//
//            fos = new FileOutputStream(zipFile);
//            zos = new ZipOutputStream(new BufferedOutputStream(fos));
//            byte[] bufs = new byte[1024 * 10];
//            for(File file1 : sourceFiles){
//                ZipEntry zipEntry = new ZipEntry(file1.getName());
//                zos.putNextEntry(zipEntry);
//
//                //读取待压缩的文件并写进压缩包里
//                fis = new FileInputStream(file1);
//                bis = new BufferedInputStream(fis, 1024*10);
//                int read = 0;
//                while((read=bis.read(bufs, 0, 1024*10)) != -1){
//                    zos.write(bufs,0,read);
//                }
//            }
//
//            return new ApiResult().success(AppConstant.MSG_SUCCESS, "模板导出成功", null);
//        }catch(Exception ex){
//            return new ApiResult().success(AppConstant.MSG_FAILURE, "模板导出失败", null);
//        } finally {
//            //关闭流
//            try {
//                if(null != bis) bis.close();
//                if(null != zos) zos.close();
//            } catch (IOException e) {
//                return new ApiResult().success(AppConstant.MSG_FAILURE, "模板导出失败", null);
//            }
//        }

//        char [] stack = new char[1024];
//        int top=-1;
//
//        String string = object.toString();
//
//        StringBuffer sb = new StringBuffer();
//        char [] charArray = string.toCharArray();
//        for(int i=0;i<charArray.length;i++){
//            char c= charArray[i];
//            if ('{' == c || '[' == c) {
//                stack[++top] = c;
//                sb.append("\n"+charArray[i] + "\n");
//                for (int j = 0; j <= top; j++) {
//                    sb.append("\t");
//                }
//                continue;
//            }
//            if ((i + 1) <= (charArray.length - 1)) {
//                char d = charArray[i+1];
//                if ('}' == d || ']' == d) {
//                    top--;
//                    sb.append(charArray[i] + "\n");
//                    for (int j = 0; j <= top; j++) {
//                        sb.append("\t");
//                    }
//                    continue;
//                }
//            }
//            if (',' == c) {
//                sb.append(charArray[i] + "");
//                for (int j = 0; j <= top; j++) {
//                    sb.append("");
//                }
//                continue;
//            }
//            sb.append(c);
//        }

//        Writer write = new FileWriter(file);
//        write.write(sb.toString());
//        write.flush();
//        write.close();
//    }

    /**
     * 获取模板一览数据
     *
     * @return
     */
    @Override
    public ApiResult getModelMainList() {
        // 返回对象
        List<ModelMainModel> modelList = new ArrayList<ModelMainModel>();

        // 查询获取元对象
        ModelMainModel modelModel = new ModelMainModel();
        List<ModelMainModel> list = modelMainMapper.findAllModelMainControl(modelModel);

        // 是否同一模板ID
        String guid = "";

        // 同一模板的栏目配置
        List<ModelControlMapModel> mapList = new ArrayList<ModelControlMapModel>();

        for (int i = 0; i < list.size(); i++) {
            ModelMainModel model = list.get(i);
            // 第一个对象
            if ("".equals(guid)) {
                guid = model.getGuid();
                mapList.add(setModelMapBean(model));
            } else {
                if (guid.equals(model.getGuid())) {
                    mapList.add(setModelMapBean(model));
                } else {
                    guid = model.getGuid();
                    ModelMainModel mainModel = list.get(i - 1);
                    mainModel.setModelControlList(mapList);
                    modelList.add(mainModel);
                    mapList = new ArrayList<ModelControlMapModel>();
                    mapList.add(setModelMapBean(model));
                }
            }

            // 最后一个对象
            if (i == list.size() - 1) {
                model.setModelControlList(mapList);
                modelList.add(model);
            }
        }

        for (ModelMainModel modelMainModel : modelList) {
            modelMainModel.setThumbnail(BaseConstant.getServerConfig().getUrl() + "/template" + "/" + modelMainModel.getNo() + "/" + modelMainModel.getThumbnail());
        }
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "获取模板成功", modelList);
    }

    private void AddControlList(ModelMainModel modelMain, List<ModelMainModel> list) {
        modelMain.setModelControlList(new ArrayList<>());
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getGuid().equals(modelMain.getGuid())) {
                modelMain.getModelControlList().add(setModelMapBean(list.get(i)));
            }
        }
    }

    @Override
    public ApiResult getModelMainListByStyleId(String styleId) {

        List<ModelMainModel> modelList = new ArrayList<ModelMainModel>();

        // 查询获取元对象
        ModelMainModel modelModel = new ModelMainModel();
        List<ModelMainModel> list = null;
        if (styleId.equals("-1")) {
            list = modelMainMapper.findAllModelMainControl(modelModel);
        } else {
            list = modelMainMapper.findModelMainControlByStyleId(styleId);
        }


        // 同一模板的栏目配置
        List<ModelControlMapModel> mapList = new ArrayList<ModelControlMapModel>();

        // 构建modellist对象
        for (int i = 0; i < list.size(); i++) {
            ModelMainModel model = list.get(i);

            // 区域名
//            if(StringUtils.isNotEmpty(model.getAreanoname())){
//                model.setAreano(model.getAreanoname() + "(" + model.getAreano() + ")");
//            }

            if (modelList.size() == 0) {
                model.setThumbnail(BaseConstant.getServerConfig().getMediaurl() + "/template" + "/" + model.getNo() + "/" + model.getThumbnail());
                AddControlList(model, list);
                modelList.add(model);
            } else {
                boolean isexists = false;
                for (int j = 0; j < modelList.size(); j++) {
                    if (modelList.get(j).getGuid().equals(list.get(i).getGuid())) {
                        isexists = true;
                        break;
                    }
                }
                if (!isexists) {
                    model.setThumbnail(BaseConstant.getServerConfig().getMediaurl() + "/template" + "/" + model.getNo() + "/" + model.getThumbnail());
                    AddControlList(model, list);
                    modelList.add(model);
                }
            }
        }

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "获取模板成功", modelList);
    }

    @Override
    public List<ModelMainModel> getDefaultStyleModels() {
        String defaultStyleId = iSysService.findGlobalConfig().getDefaultstyleid();
        return (List<ModelMainModel>) getModelMainListByStyleId(defaultStyleId).getData();
    }

    @Override
    public List<StlDevMap> getDevsByStyleId(String styleId) {
        List<StlDevMap> devs = stlDevMapMapper.getDevByStyleId(styleId);
        return devs;
    }

    @Override
    public List<EquipmentAndSiteModel> getEquipmentAndSiteByStyleId(String styleId) {
        List<EquipmentAndSiteModel> devs = stlDevMapMapper.getEquipmentAndSiteByStyleId(styleId);
        return devs;
    }

    /**
     * 判断导入的模板是否重复
     *
     * @param modelMainModel
     * @return
     */
    @Override
    @Transactional
    public ApiResult isRepeated(ModelMainModel modelMainModel) {
        List<ModelMainModel> modelMainModelList = modelMainMapper.selectByNoAndNameAndSortid(modelMainModel);
        //System.out.println("长度:"+modelMainModelList.size());
        if (modelMainModelList.size() > 0) {
            return new ApiResult<>(AppConstant.MSG_FAILURE, false);
        }
        //System.out.println("导入成功");
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true);

    }

    /**
     * 根据模板id删除模板
     *
     * @param guid 模板id
     * @return
     */
    @Override
    public ApiResult deleteModelMain(String guid) {
        int rt = modelMainMapper.updateDeleteByPrimaryKey(guid);
        if (rt > 0) {
            return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "删除模板成功", null);
        }
        return new ApiResult<>(AppConstant.MSG_FAILURE, true, "删除模板失败", null);
    }

    /**
     * 修改默认式样的默认模板
     *
     * @param guid
     * @param name
     * @return
     */
    @Override
    public ApiResult editDefaultModel(String guid, String name) {
        //找到默认式样的guid即styleid
        ModelMain modelMain = modelMainMapper.selectByName(name);
        //System.out.println("式样id:"+modelMain.getGuid());
        int result = 0;
        if (null != modelMain) {
            List<StlModelMainMap> stlModelMainMapList1 = modelMainMapper.selectByStyleid(modelMain.getGuid());
            if (null != stlModelMainMapList1 && stlModelMainMapList1.size() > 0) {
                //根据样式id找到该式样的设置模版的信息
                StlModelMainMap stlModelMainMap = new StlModelMainMap();
                stlModelMainMap.setStyleid(modelMain.getGuid());
                stlModelMainMap.setModelid(guid);
                StlModelMainMap stlModelMainMapList = modelMainMapper.selectByStlModelMainMap(stlModelMainMap);
                if (null != stlModelMainMapList) {
                    //根据式样id改变默认式样的isdefault为0;
                    result = modelMainMapper.updateByStyleid(modelMain.getGuid());
                    //修改该默认模板
                    stlModelMainMapList.setIsdefault(1);
                    modelMainMapper.updateByStlModelMainMap(stlModelMainMap);
                    return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "默认式样的默认模板修改成功");
                } else {
                    return new ApiResult<>(AppConstant.MSG_FAILURE, false, "该式样暂无该模板,修改失败");
                }
            } else {
                return new ApiResult<>(AppConstant.MSG_FAILURE, false, "该式样暂无该模板");
            }

        } else {
            return new ApiResult<>(AppConstant.MSG_FAILURE, false, "找不到默认式样");
        }

    }

    @Override
    public List<SimpleModel> findModels() {
        List<SimpleModel> simpleModels = null;
        List<ModelMain> models = modelMainMapper.findModels();
        if (models != null) {
            simpleModels = new ArrayList<>();
            for (ModelMain modelMain : models) {
                SimpleModel simpleModel = new SimpleModel();
                simpleModel.setNo(modelMain.getNo());
                simpleModel.setName(modelMain.getName());
                simpleModel.setUrl(modelMain.getUrl() + ".zip");
                simpleModel.setDirect(modelMain.getDirect());
                simpleModels.add(simpleModel);
            }
        }
        return simpleModels;
    }

    @Override
    public ApiResult countModel(String guid) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, modelMainMapper.selectCountModel(guid));
    }

    @Override
    public ApiCode updateDefaultStyleModelId(String styleId, String defaultModelId) {
        ApiCode apiCode = ApiCode.APP_100200;
        stlModelMainMapMapper.updateNoneDefaultByStyleId(styleId);
        stlModelMainMapMapper.updateDefaultStyleModelId(styleId, defaultModelId);
        return apiCode;
    }

    @Override
    public ApiCode updateDefaultStyleModelProgram(String styleId, String defaultModelId) {
        ApiCode apiCode = ApiCode.APP_100200;

        // 获取模板下区域集合
        List<ModelControlModel> modelControlModels = modelControlMapper.findAllModelControlByModelId(defaultModelId);

        // 设定模板区域对应的节目ID
        jmControlMapMapper.deleteJmAndControlMapByStyleId(styleId, defaultModelId);

        // 获取全局配置中的媒体ID和公告ID集合
        String globalMediaIds = iSysService.findGlobalConfig().getDefaultmediaids();
        String globalNoticeIds = iSysService.findGlobalConfig().getDefaultnoticeids();

        // 获取全局配置默认媒体类节目ID集合
        String[] mediaIds = globalMediaIds.split(",");
        // 获取全局配置默认公告类节目ID集合
        String[] noticeIds = globalNoticeIds.split(",");

        int i = 0, j = 0;
        for (ModelControlModel controlModel : modelControlModels) {

            if(controlModel.getSourcetype().equals("0") ||
                    controlModel.getSourcetype().equals("1")) {

                JmControlMap jmControlMap = new JmControlMap();
                jmControlMap.setGuid(UUID.randomUUID().toString());

                if (controlModel.getSourcetype().equals("0")) {
                    if (i >= mediaIds.length) {
                        i = 0;
                    }
                    jmControlMap.setJmid(mediaIds[i++]);
                }

                if (controlModel.getSourcetype().equals("1")) {
                    if (j >= noticeIds.length) {
                        j = 0;
                    }
                    jmControlMap.setJmid(noticeIds[j++]);
                }

                jmControlMap.setControlid(controlModel.getGuid());
                jmControlMap.setModelid(defaultModelId);
                jmControlMap.setCreatetime(new Date());
                jmControlMap.setRegioncode(controlModel.getRegioncode());
                jmControlMap.setStyleid(styleId);
                jmControlMapMapper.insert(jmControlMap);
            }
        }

        return apiCode;
    }
}
